﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using LeShiTao_Library.WeChat.Public_WC;

namespace TB_WS.Class
{
    public class HongBao_Logic
    {
        /// <summary>
        /// 根据QR码的scene_id获取是否在数据库存在
        /// </summary>
        /// <param name="QR_scene_id">QR_scene_id</param>
        /// <returns></returns>
        public static int get_QR_scene_count(string QR_scene_id)
        {
            string sql = "select count(*) from HongBao_List where QR_scene_id='" + QR_scene_id + "'";
            return Convert.ToInt32(Unit.db_Conn.scalar(sql));
        }


        /// <summary>
        /// 根据QR_scene_id 获取QR详情
        /// </summary>
        /// <param name="QR_scene_id">QR_scene_id码</param>
        /// <returns></returns>
        public static DataSet get_QR_scene_info(string QR_scene_id)
        {
            string sql = "select * from HongBao_List where QR_scene_id='" + QR_scene_id + "'";
            return Unit.db_Conn.select(sql);
        }

        /// <summary>
        /// 根据QR_URL 获取QR详情
        /// </summary>
        /// <param name="QR_URL">QR_URL</param>
        /// <returns></returns>
        public static DataSet get_QR_scene_info_URL(string QR_URL)
        {
            string sql = "select * from HongBao_List where QR_URL='" + QR_URL + "'";
            return Unit.db_Conn.select(sql);
        }

        /// <summary>
        /// 根据订单号 Tid 获取QR详情
        /// </summary>
        /// <param name="Tid">订单号</param>
        /// <returns></returns>
        public static DataSet get_QR_scene_info_use_Tid(string Tid)
        {
            string sql = "select * from HongBao_List where Tids like '%" + Tid + "%'";
            return Unit.db_Conn.select(sql);
        }

        /// <summary>
        /// 新增一个红包
        /// </summary>
        /// <param name="Seller_ID">卖家编号id</param>
        /// <param name="QR_scene_id">QR码编号</param>
        /// <param name="QR_ticket">QR ticket</param>
        /// <param name="Tids">订单编号List</param>
        /// <param name="Money">红包金额</param>
        /// <param name="Create_From">创建来源</param>
        /// <returns></returns>
        public static int insert_QR_Info(int Seller_ID,
            string QR_scene_id, string QR_ticket, string Tids,
            int Money, string Create_From,string Type)
        {
            string sql = "insert into HongBao_List values(" + Seller_ID + ",'" + QR_scene_id
                + "','" + QR_ticket + "','" + Tids + "','" +
                LeShiTao_Library.Tools.Data_Handle.GET_UNIX_TIMESTAMP().ToString() +
                "'," + Convert.ToInt32(Money) + ",'" +
                Create_From + "','"+Type+"',' ')";
            return Unit.db_Conn.Nonquery(sql);
        }


        /// <summary>
        /// 修改QR码红包金额
        /// </summary>
        /// <param name="QR_scene_id">QR码唯一编码</param>
        /// <param name="Money">红包金额</param>
        /// <returns></returns>
        public static int update_Money(string QR_scene_id,int Money)
        {
            string sql = "update HongBao_List set Money=" + Money + " where QR_scene_id='" + QR_scene_id + "'";
            return Unit.db_Conn.Nonquery(sql);
        }


        /// <summary>
        /// 获取待打印红包数量
        /// </summary>
        /// <param name="Seller_ID">商户编号</param>
        /// <returns></returns>
        public static int get_HB_None_Count(int Seller_ID)
        {
            string sql = "select count(*) from HongBao_List where Type='Wait_Print' and Seller_ID="+Seller_ID;
            return Convert.ToInt32(Unit.db_Conn.scalar(sql));
        }



        /// <summary>
        /// 获取待打印列表
        /// </summary>
        /// <param name="Seller_ID">商户编号</param>
        /// <param name="Max">最大获取数量</param>
        /// <returns></returns>
        public static DataSet GET_HB_NONE_LIST(int Seller_ID,int Max)
        {
            string sql = "select top "+Max.ToString()+" * from HongBao_List where Type='Wait_Print' and Seller_ID=" + Seller_ID+" order by id desc";
            return Unit.db_Conn.select(sql);
        }


        /// <summary>
        /// 匹配红包
        /// </summary>
        /// <param name="QR_URL">QR码链接</param>
        /// <param name="Tids">订单号</param>
        /// <param name="Money">金额</param>
        /// <param name="Type">类型</param>
        /// <returns>返回执行是否成功</returns>
        public static int Mate_HB(string QR_URL,string Tids,int Money,string Type)
        {
            string sql = "update HongBao_List set Tids='" + Tids + "',Money=" + (Money*100) + ",Type='"+Type+"' where QR_URL='" + QR_URL + "'";
            return Unit.db_Conn.Nonquery(sql);
        }

        /// <summary>
        /// 更新红包状态
        /// </summary>
        /// <param name="QR_scene_id">QR码唯一scene</param>
        /// <param name="Type">更新状态信息</param>
        /// <param name="contet">更新备注  待领取：Wait_Collect    待领取回评返现红包：Wait_Collect_2    已领取：Collected   作废：End  
        ///     待打印红包：Wait_Print      待关联红包：Wait_Mate</param>
        /// <returns></returns>
        public static int update_Type(string QR_scene_id,string Type,string contet)
        {
            string sql = "update HongBao_List set Type='" + Type +
                "',contet='" + contet + "' where QR_scene_id='" +
                QR_scene_id + "'";
            return Unit.db_Conn.Nonquery(sql);
        }


        /// <summary>
        /// 新增红包--服务器端
        /// </summary>
        /// <param name="Seller_ID">卖家编号</param>
        /// <param name="WX_User">微信用户</param>
        /// <param name="Create_From">来自于</param>
        /// <param name="Tids">订单号</param>
        /// <param name="Money">金额</param>
        /// <param name="Type">状态</param>
        /// <returns></returns>
        public static string insert_HB_Server(int Seller_ID,string WX_User,
            string Create_From,string Tids,double Money,string Type)
        {
            string RT_Str = "";
            int RT_Type = 0;

            string scene_id;
            string JSON_Ticket;
            string QR_URL;

            Random rd = new Random();
            
            int scene_count;
            do
            {
                scene_id = rd.Next(1, 2147483646).ToString();
                scene_count = get_QR_scene_count(scene_id);
            } while (scene_count != 0);
            string BR_JSON = LeShiTao_Library.WeChat.Public_WC.BarCode.Create_Temp_BarCode(
                        Convert.ToInt32(scene_id), WX_User.Trim().ToString(), "2592000");
            JSON_Ticket = LeShiTao_Library.WeChat.Public_WC.BarCode.GET_Ticket(BR_JSON);
            if (JSON_Ticket == "4001")
            { //返现错误
                RT_Type = 1;
                RT_Str = "返现出现错误：" + BR_JSON.ToString()+"\n\n请重新发放红包";
            }
            else if (JSON_Ticket == "41001")
            { //返现错误
                RT_Type = 1;
                RT_Str = "返现出现错误 错误类型：缺少AccessToken参数 错误XML码：" + BR_JSON.ToString() + "\n\n请重新发放红包";
            }
            else if (JSON_Ticket == "40001")
            { //返现错误
                Access_Token AT = new Access_Token(WX_User);
                AT.Create_Public_access_token();//创建一个新的ACCESSTOKEN
                RT_Type = 1;
                RT_Str = "返现出现错误 错误类型：获取access_token时AppSecret错误，或者access_token无效 错误XML码：" + BR_JSON.ToString() + "\n\n该问题已自动修复\n请重新发放红包即可";
            }
            else
            {
                QR_URL = LeShiTao_Library.WeChat.Public_WC.BarCode.GET_QR_URL(BR_JSON);
                if (QR_URL == "")
                {
                    RT_Type = 1;
                    RT_Str = "返现出现错误：获取QR_URL出现异常，异常XML：" + BR_JSON.ToString()+"\n\n请重新发放红包";
                }
                else
                {
                    string sql = "insert into HongBao_List values(" + Seller_ID + ",'" + scene_id
                        + "','" + JSON_Ticket + "','" + Tids + "','" +
                        LeShiTao_Library.Tools.Data_Handle.GET_UNIX_TIMESTAMP().ToString() +
                        "'," + Convert.ToInt32(Money * 100) + ",'" +
                        Create_From + "','" + Type + "',' ','"+QR_URL+"')";
                    int SQL_Count = Class.Unit.db_Conn.Nonquery(sql);
                    if (SQL_Count == 1)
                    {
                        //正确 可以抛出数据
                        RT_Str = scene_id + "#" + JSON_Ticket + "#" + QR_URL;
                    }
                    else
                    {
                        //提交失败
                        RT_Type = 1;
                        RT_Str = "返现出现错误 请重试";
                    }
                }
            }
            return RT_Type + "@" + RT_Str;
        }




       
    }
}
